<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-if="optType !='view' && optType != 'execute' "
          v-hasPermi="['rr:requisitionline:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="requisitionlineList" @selection-change="handleSelectionChange" border>
      <el-table-column label="序号"  type="index" width="50"/>
      <el-table-column label="物料编码" align="center" prop="itemCode" />
      <el-table-column label="物料名称" align="center" prop="itemName" />
      <el-table-column label="规格型号" align="center" prop="specification" />
      <el-table-column label="单位（主）" align="center" prop="unitOfMeasure" />
      <el-table-column label="领料数量（主）" align="center" prop="quantityIssued" />
      <el-table-column label="单位（辅）" align="center" prop="storageUnit"  />
      <el-table-column label="出库数量（辅）" align="center"   prop="storageUnitquantity" >
        <template slot-scope="scope">
          <el-tag type="success" v-if="'Y' == scope.row.enableMultiUnit">{{ scope.row.storageUnitquantity }}</el-tag>
          <span v-else></span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width"  v-if="optType !='view' ">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['rr:requisitionline:edit']"
            v-if="optType !='view' && optType != 'execute' "
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="optType !='view' && optType != 'execute' "
            v-hasPermi="['rr:requisitionline:remove']"
          >删除</el-button>
          <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleChoose(scope.row)"
              v-if="optType == 'execute'"
              v-hasPermi="['wm:issueother:edit']"
          >选择
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <StockChooseSelect
        ref="stockSelect"
        :itemCode="selectedItemCode"
        :enable-multi-unit="selectedEnableMultiUnit"
        :storage-unit-type="selectedStorageUnitType"
        :storage-ratio="selectedStorageRatio"
        @onSelected="onStockSelected"
    />
    <!-- 添加或修改返修领料单体对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="960px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="物料编码" prop="itemCode" readonly>
              <el-input v-model="form.itemCode" readonly="readonly" placeholder="请选择产品物料编码">
                <el-button slot="append" @click="handleSelectStock" icon="el-icon-search"></el-button>
              </el-input>
            </el-form-item>
<!--            <StockSelect ref="stockSelect" @onSelected="onStockSelected"  ></StockSelect>-->
            <!--                支取人只选择支取什么物料，使用物料弹框  20250704改功能-->
            <ItemSelect ref="itemSelect" @onSelected="onItemSelected"></ItemSelect>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="itemName">
              <el-input v-model="form.itemName" placeholder="请输入物料名称" readonly/>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="规格型号" prop="specification">
              <el-input v-model="form.specification" placeholder="请输入规格型号" readonly/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="单位（主）" prop="unitOfMeasure"  >
              <el-input v-model="form.unitOfMeasure" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料数量（主）" prop="quantityIssued" label-width="100" style="width: 100%">
              <el-input-number :min=0  v-model="form.quantityIssued"  @change="handleChangeZhu" placeholder="请输领料数量" />
            </el-form-item>
          </el-col>

        </el-row>
        <el-row :gutter="20" v-if="form.enableMultiUnit === 'Y'">
          <el-col :span="12">
            <el-form-item label="单位（辅）" prop="storageUnit" >
              <el-input v-model="form.storageUnit" readonly="readonly" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="领料数量（辅）" prop="storageUnitquantity" label-width="100" style="width: 100%">
              <el-input-number :min=0  v-model="form.storageUnitquantity" @change="handleChangeFu" placeholder="请输入出库数量"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="form.enableMultiUnit === 'Y'">
          <el-col :span="12">
            <el-form-item label="换算方式" prop="storageUnitType">
              <el-input :value="form.storageUnitType === 'fixed' ? '固定' : '浮动'"  readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="换算比例" prop="storageRatio">
              <el-input-number
                :min="0"
                v-model="form.storageRatio"
                disabled
              />
            </el-form-item>
          </el-col>
        </el-row>
<!--        <el-row>
          <el-col :span="8">
            <el-form-item label="仓库" prop="warehouseName">
              <el-input v-model="form.warehouseName" placeholder="请输入仓库" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库区" prop="locationName">
              <el-input v-model="form.locationName" placeholder="请输入库区" readonly/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库位" prop="areaName">
              <el-input v-model="form.areaName" placeholder="请输入库位" readonly/>
            </el-form-item>
          </el-col>
        </el-row>-->
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequisitionline, getRequisitionline, delRequisitionline, addRequisitionline, updateRequisitionline } from "@/api/mes/rr/requisitionline";
import { listRequisitionapplay, getRequisitionapplay, delRequisitionapplay, addRequisitionapplay, updateRequisitionapplay } from "@/api/mes/rr/requisitionapplay";

// import StockSelect from "@/components/stockSelect/single.vue";
import ItemSelect from "@/components/itemSelect/single.vue";
import {getMdItem} from "@/api/mes/md/mdItem";
import StockChooseSelect from "@/components/issueChooseSelect/singlemultiunit.vue"
import StockSelect from "@/components/issueChooseSelect/singlemultiunit.vue";
import {addIssueline} from "@/api/mes/wm/issuelineother";
import {addIssuseapplyother, updateIssuseapplyother} from "@/api/mes/wm/issuseapplyother";
import Template from "@/views/print/printtemplate/list.vue";
export default {
  name: "RequisitionApplayline",
  components: {Template, StockSelect, ItemSelect,StockChooseSelect},
  props: {
    optType: null,
    orderId: null,

  },
  data() {
    return {
      selectedItemCode: null,
      selectedEnableMultiUnit:"N",
      selectedStorageUnitType: null,
      selectedStorageRatio: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 返修领料单体表格数据
      requisitionlineList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderId:this.orderId,
        itemCode: null,        itemName: null,      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        itemCode: [
          {required: true, message: "物料编码不能为空", trigger: "blur"}
        ],
        quantityIssued: [
          {required: true, message: "领料数量不能为空", trigger: "blur"},
          { validator: this.checkQuantity, trigger: 'blur' }
        ],
      }
    };
  },
  created() {
    console.log("createtttttt",this.requisitionlineList)
    this.getList();
  },
  methods: {
    checkQuantity(rule, value, callback) {
      if (value <= 0) {
        return callback(new Error('领料数量必须大于0'));
      }
      callback(); // 如果值大于0，则通过校验
    },
    /** 查询返修领料单体列表 */
    getList() {
      if(this.orderId){
        console.log("33333")
        this.loading = true;
        listRequisitionapplay(this.queryParams).then(response => {
          this.requisitionlineList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log('getlistggggggg',this.requisitionlineList)
        });
      }else{
        this.loading = false
      }
      // this.$emit('change',this.requisitionlineList);
    },
    handleChoose(row){
      this.selectedItemCode = row.itemCode;
      this.selectedEnableMultiUnit = row.enableMultiUnit;
      this.selectedStorageUnitType = row.storageUnitType;
      this.selectedStorageRatio = row.storageRatio;
      this.$refs.stockSelect.showFlag = true;
    },
    handleChangeZhu(value) {
      if ('Y' == this.form.enableMultiUnit) {
        if (this.form.storageUnitType === 'fixed') {
          // 库存单位数量=主数量 / 换算比例
          this.form.storageUnitquantity = parseFloat(
            (this.form.quantityIssued / this.form.storageRatio).toFixed(7)
          );
        }
        //浮动换算就得 填写两个数量计算出浮动率就可以了
        if (this.form.storageUnitType === 'float') {
          this.handleFloatCalculate()
        }
      }
    },
    handleChangeFu() {
      if (this.form.storageUnitType === 'fixed') {
        // 主数量 = 库存单位数量 * 换算比例
        this.form.quantityIssued = parseFloat(
          (this.form.storageUnitquantity * this.form.storageRatio).toFixed(7)
        );
      }
      //浮动换算就得 填写两个数量计算出浮动率就可以了
      if (this.form.storageUnitType === 'float') {
        this.handleFloatCalculate()
      }

    },
    handleFloatCalculate(triggerSource) {
      //浮动就根据两个数量计算出浮动率就可以了
      if (this.form.storageUnitType !== 'float') return;

      if (this.form.storageUnitquantity > 0 && this.form.quantityIssued > 0) {
        console.log("mmmmmmmmmmmm")
        // 计算新换算比例 = 主数量 / 库存单位数量
        this.form.storageRatio = parseFloat(
          (this.form.quantityIssued / this.form.storageUnitquantity).toFixed(4)
        );
      }
    },
    handleSelectStock() {
   /*   this.$refs.stockSelect.showFlag = true;
      this.$refs.stockSelect.getList();*/
      this.$refs.itemSelect.showFlag = true;
      this.$refs.itemSelect.getList();
    },
    //物料选择弹出框
    onItemSelected(obj) {
      if (obj != undefined && obj != null) {


        getMdItem(obj.itemId).then(response => {
          this.form.enableMultiUnit = response.data.enableMultiUnit
          this.form.storageUnit = response.data.storageUnit
          this.form.storageUnitType = response.data.storageUnitType
          this.form.storageRatio = response.data.storageRatio

          this.form.itemId = obj.itemId;
          this.form.itemCode = obj.itemCode;
          this.form.itemName = obj.itemName;
          this.form.specification = obj.specification;
          this.form.unitOfMeasure = obj.unitOfMeasure;
          this.form.quantityIssued = obj.quantityOnhand;
        })
      }
    },
    //物料选择弹出框
    onStockSelected(stockInfo) {
      this.reset()
      if (stockInfo != undefined && stockInfo != null) {
        console.log("sssssss", stockInfo)
        this.lineForm = {
          ...this.lineForm,
          orderId: this.orderId,
          materialStockId: stockInfo.materialStockId,
          itemId: stockInfo.itemId,
          itemCode: stockInfo.itemCode,
          itemName: stockInfo.itemName,
          specification: stockInfo.specification,
          unitOfMeasure: stockInfo.unitOfMeasure,
          batchCode: stockInfo.batchCode,
          workorderId: stockInfo.workorderId,
          workorderCode: stockInfo.workorderCode,
          warehouseId: stockInfo.warehouseId,
          warehouseCode: stockInfo.warehouseCode,
          warehouseName: stockInfo.warehouseName,
          locationId: stockInfo.locationId,
          locationCode: stockInfo.locationCode,
          locationName: stockInfo.locationName,
          areaId: stockInfo.areaId,
          areaCode: stockInfo.areaCode,
          areaName: stockInfo.areaName,
          quantityIssued: stockInfo.quantityOutPrimary,
          storageUnitquantity: stockInfo.quantityOutWarehouse,
          storageUnit: stockInfo.storageUnit,
          storageUnitType: stockInfo.storageUnitType,
          storageRatio: stockInfo.storageRatio,
          enableMultiUnit:stockInfo.enableMultiUnit,
          price: stockInfo.price,
          quantityMax: stockInfo.quantityOnhand
        };
        addRequisitionline(this.lineForm).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.$refs.stockSelect.showFlag = false;
          this.$emit('call-get-list');
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,        orderId: this.orderId,        materialStockId: null,        itemId: null,        itemCode: null,        itemName: null,        specification: null,        unitOfMeasure: null,
        quantityIssued: null,        batchCode: null,        warehouseId: null,        warehouseCode: null,        warehouseName: null,        locationId: null,        locationCode: null,        locationName: null,        areaId: null,        areaCode: null,        areaName: null,
        remark: null,        createBy: null,        createTime: null,        createByName: null,        updateBy: null,        updateTime: null,        tenantId: null
        ,enableMultiUnit:null,
        storageUnit:null,
        storageUnitType:null,
        storageRatio:null,
        storageUnitquantity:null

      };
      this.resetForm("form");

    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加返修领料单体";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
   /*   // 直接使用当前行数据（不再调用API） 这个是单据头体一起保存
      this.form = {...row};  // 使用浅拷贝
      this.open = true;
      this.title = "修改返修领料";*/
      // 单据头体 分开保存
      const id = row.id || this.ids
      getRequisitionapplay(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改返修领料单体";
      });
    },
    /** 提交按钮   实现 整体单据点击保存的时候，修改才真正修改*/
/*    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 新增：判断是新增还是修改操作
          if (this.form.id) {
            // 修改现有行
            const index = this.requisitionlineList.findIndex(tableitem => tableitem.id === this.form.id);
            if (index !== -1) {
              this.requisitionlineList.splice(index, 1, {...this.form});
            }
          } else {
            // 新增行
            // 添加orderId关联
            this.form.orderId = this.orderId;
            this.requisitionlineList.push({...this.form});
          }

          this.open = false;
          // 触发事件通知父组件
          this.$emit('change',this.requisitionlineList);

        }
      });
    },*/
    // 提交就直接保存，跟大家保持一致  先天单据头  然后天单据体
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.quantityIssued <= 0) {
            this.$modal.msgError("领料数量（主）必须大于0");
            return
          }

          if (this.enableMultiUnit == 'Y') {
            if (this.form.storageUnitquantity <= 0) {
              this.$modal.msgError("领料数量（辅）必须大于0");
              return
            }
          }
          if (this.form.id != null) {
            updateRequisitionapplay(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRequisitionapplay(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
 /*  删除时 点击父类的确认  才删除
  // 删除时  已有ID的行通过ID删除 五id直接找到对象删除
      if (row.id) {
        // 已有ID的行通过ID删除
        const index = this.requisitionlineList.findIndex(item => item.id === row.id);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      } else {
        // 新增的删除
        const index = this.requisitionlineList.indexOf(row);
        if (index !== -1) {
          this.requisitionlineList.splice(index, 1);
        }
      }
      // 重置选中状态
      this.ids = [];
      this.single = true;
      this.multiple = true;
      this.$emit('change', this.requisitionlineList);*/
      // 直接从单据体删除
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delRequisitionapplay(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('rr/requisitionapplay/export', {
        ...this.queryParams
      }, `requisitionapplay_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
